#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""

@author ：chenzf
@date ：2024/4/23 下午12:18 
"""
import decimal
import json

from pymysql import Connection

from data_demo.file_define import JsonFileReader
from data_demo.my_data import Record
from mysql_demo.MyEncoder import MyEncoder


def object_to_json(record):
    return {
        "date": record.date,
        "order_id": record.order_id,
        "money": record.money,
        "province": record.province
    }


# 连接数据库
conn = Connection(host="192.168.108.100", port=3306, user="root", password="123456", autocommit=True)
cursor = conn.cursor()  # 获取游标
conn.select_db("dev_new")  # 选择数据库
try:
    # 数据查询
    # cursor.execute("select * from student")
    # for row in cursor:
    #     print(row)
    # cursor.execute("delete from student where id = 1")
    # 数据插入
    # json_data = JsonFileReader("../data_demo/sale_json_data.txt").read_data()
    # for data in json_data:
    #     cursor.execute(f"insert into orders (date,order_id, money, province) "
    #                    f"values('{data.date}','{data.order_id}', {data.money}, '{data.province}')")
    cursor.execute("select * from orders")
    dict_arr = []
    object_arr: list[Record] = []
    for row in cursor:
        # 在python中对象数组是是无法直接转换为json的，所以需要将数据转换为字典类型
        dict_arr.append(
            Record(date=row[1], order_id=row[2], money=decimal.Decimal(row[3]).__float__(), province=row[4]).__dict__)
        # dict_arr.append(Record(date=row[1], order_id=row[2], money=float(row[3]), province=row[4]).__dict__)
        object_arr.append(Record(date=row[1], order_id=row[2], money=float(row[3]), province=row[4]))
    print(json.dumps(dict_arr, ensure_ascii=False))
    print(json.dumps(object_arr,
                     default=object_to_json
                     ))
except EOFError as e:
    conn.rollback()
    print(e)
finally:
    cursor.close()
    conn.close()
